package com.gitee.jnxj.nraft.autoconfigure;

import com.gitee.jnxj.nrpc.spring.boot.autoconfigure.config.RpcServerConfig;
import com.google.auto.service.AutoService;
import org.example.nrpc.register.api.RegisterConsumer;
import org.example.nrpc.register.api.RpcRegister;
import org.example.nrpc.register.api.model.RpcServiceInstance;

/**
 * @author 江南小俊
 * @since 2021/7/12
 */
@AutoService(RpcRegister.class)
public class NRaftRegister implements RpcRegister {
    private NRaftConfig nRaftConfig;
    private RpcServerConfig self;

    @Override
    public void init(String connectString) {
        nRaftConfig = NRaftAutoConfiguration.getApplicationContext().getBean(NRaftConfig.class);
        self = NRaftAutoConfiguration.getApplicationContext().getBean(RpcServerConfig.class);
    }

    @Override
    public void register(RpcServiceInstance rpcServiceInstance) throws Exception {

    }

    @Override
    public void addListener(String serviceName, RegisterConsumer<RpcServiceInstance> consumer) {
        for (NRaft nRaft : nRaftConfig.getNodes()) {
            if (!nRaft.getAddress().equals(self.getAddress()) || !nRaft.getPort().equals(self.getPort())) {
                consumer.accept(RpcServiceInstance.builder()
                        .serviceName(serviceName)
                        .address(nRaft.getAddress())
                        .port(nRaft.getPort())
                        .build());
            }

        }

    }

    @Override
    public void destroy() {

    }
}
